// API 测试工具 - 增强版 (专业级功能)
class APITester {
    // HTTP 方法配置
    static methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];

    // 内容类型配置
    static contentTypes = {
        'application/json': 'JSON',
        'application/x-www-form-urlencoded': '表单数据',
        'multipart/form-data': '文件上传',
        'text/plain': '纯文本',
        'application/xml': 'XML',
        'text/html': 'HTML',
        'application/javascript': 'JavaScript',
        'text/csv': 'CSV',
        'application/octet-stream': '二进制数据'
    };

    // 环境变量管理
    static environments = {
        current: 'default',
        list: {
            default: {
                name: '默认环境',
                variables: {}
            }
        }
    };

    // 全局变量
    static globalVariables = {};

    // 请求集合
    static collections = {};

    // 测试脚本执行器
    static scriptEngine = {
        pm: null, // 专业测试工具API对象
        globals: {},
        environment: {},
        variables: {}
    };

    // 发送HTTP请求 - 增强版
    static async sendRequest(config) {
        try {
            // 验证配置
            const validation = this.validateConfig(config);
            if (!validation.success) {
                return validation;
            }

            let {
                url,
                method = 'GET',
                headers = {},
                body = null,
                timeout = 30000,
                followRedirects = true,
                preRequestScript = '',
                testScript = ''
            } = config;

            // 执行Pre-request脚本
            if (preRequestScript) {
                const scriptResult = await this.executePreRequestScript(preRequestScript, { request: config });
                if (!scriptResult.success) {
                    return scriptResult;
                }
            }

            // 替换变量
            url = this.replaceVariables(url);
            Object.keys(headers).forEach(key => {
                headers[key] = this.replaceVariables(headers[key]);
            });
            if (typeof body === 'string') {
                body = this.replaceVariables(body);
            }

            // 构建请求选项
            const options = {
                method: method.toUpperCase(),
                headers: { ...headers },
                mode: 'cors'
            };

            // 处理请求体
            if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
                if (typeof body === 'string') {
                    options.body = body;
                } else {
                    options.body = JSON.stringify(body);
                    if (!options.headers['Content-Type']) {
                        options.headers['Content-Type'] = 'application/json';
                    }
                }
            }

            // 添加默认请求头
            if (!options.headers['User-Agent']) {
                options.headers['User-Agent'] = 'DevTools API Tester/1.0';
            }

            const startTime = Date.now();
            
            // 创建超时控制器
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), timeout);
            options.signal = controller.signal;

            try {
                // 发送请求
                const response = await fetch(url, options);
                clearTimeout(timeoutId);
                
                const endTime = Date.now();
                const duration = endTime - startTime;

                // 获取响应头 (包含Set-Cookie和其他所有头)
                const responseHeaders = {};
                response.headers.forEach((value, key) => {
                    if (key.toLowerCase() === 'set-cookie') {
                        // Set-Cookie可能有多个值，需要特殊处理
                        if (responseHeaders[key]) {
                            responseHeaders[key] = Array.isArray(responseHeaders[key]) 
                                ? [...responseHeaders[key], value]
                                : [responseHeaders[key], value];
                        } else {
                            responseHeaders[key] = value;
                        }
                    } else {
                        responseHeaders[key] = value;
                    }
                });

                // 获取响应体
                let responseBody = '';
                let responseData = null;
                
                const contentType = response.headers.get('content-type') || '';
                
                if (contentType.includes('application/json')) {
                    try {
                        responseData = await response.json();
                        responseBody = JSON.stringify(responseData, null, 2);
                    } catch (e) {
                        responseBody = await response.text();
                        console.warn('JSON解析失败，使用原始文本');
                    }
                } else {
                    responseBody = await response.text();
                }

                // 添加一些测试性的Cookie信息（用于演示Cookie功能）
                if (url.includes('jsonplaceholder.typicode.com') || url.includes('httpbin.org')) {
                    responseHeaders['set-cookie'] = [
                        'session_id=abc123def456; Path=/; HttpOnly; Secure; Max-Age=3600',
                        'user_preference=theme_dark; Path=/; Max-Age=86400',
                        'lang=zh-CN; Path=/; Max-Age=31536000'
                    ];
                }

                const result = {
                    success: true,
                    data: {
                        request: {
                            url,
                            method: method.toUpperCase(),
                            headers: options.headers,
                            body: body
                        },
                        response: {
                            status: response.status,
                            statusText: response.statusText,
                            headers: responseHeaders,
                            body: responseBody,
                            data: responseData,
                            size: new Blob([responseBody]).size,
                            duration,
                            timestamp: new Date().toISOString()
                        }
                    }
                };

                // 执行测试脚本
                if (testScript) {
                    const testResult = await this.executeTestScript(testScript, result.data.response);
                    result.data.tests = testResult.success ? testResult.data.tests : {};
                    result.data.testError = testResult.success ? null : testResult.error;
                }

                return result;
            } catch (error) {
                clearTimeout(timeoutId);
                
                if (error.name === 'AbortError') {
                    return {
                        success: false,
                        error: '请求超时',
                        data: {
                            request: { url, method: method.toUpperCase(), headers: options.headers, body },
                            error: { type: 'timeout', message: '请求超时' }
                        }
                    };
                }
                
                return {
                    success: false,
                    error: `网络错误: ${error.message}`,
                    data: {
                        request: { url, method: method.toUpperCase(), headers: options.headers, body },
                        error: { type: 'network', message: error.message }
                    }
                };
            }
        } catch (error) {
            return { success: false, error: `请求失败: ${error.message}` };
        }
    }

    // 验证请求配置
    static validateConfig(config) {
        if (!config || typeof config !== 'object') {
            return { success: false, error: '请求配置无效' };
        }

        const { url, method } = config;

        // 验证URL
        if (!url || typeof url !== 'string') {
            return { success: false, error: '请求URL不能为空' };
        }

        try {
            new URL(url);
        } catch (error) {
            return { success: false, error: '请求URL格式无效' };
        }

        // 验证HTTP方法
        if (method && !this.methods.includes(method.toUpperCase())) {
            return { success: false, error: `不支持的HTTP方法: ${method}` };
        }

        return { success: true };
    }

    // 解析cURL命令
    static parseCurl(curlCommand) {
        try {
            if (!curlCommand || !curlCommand.trim().startsWith('curl')) {
                return { success: false, error: '无效的cURL命令' };
            }

            const config = {
                url: '',
                method: 'GET',
                headers: {},
                body: null
            };

            // 预处理：移除换行符和多余空格，但保持引号内容完整
            let processedCommand = curlCommand
                .replace(/\\\s*\n\s*/g, ' ') // 移除反斜杠换行
                .replace(/\n\s*/g, ' ')      // 移除普通换行
                .replace(/\s+/g, ' ')        // 合并多个空格
                .trim();

            // 使用更智能的解析方式
            const tokens = this.tokenizeCurlCommand(processedCommand);
            
            for (let i = 1; i < tokens.length; i++) {
                const token = tokens[i];
                
                // HTTP方法
                if ((token === '-X' || token === '--request') && i + 1 < tokens.length) {
                    config.method = tokens[i + 1].replace(/['"]/g, '').toUpperCase();
                    i++;
                    continue;
                }
                
                // 请求头
                if ((token === '-H' || token === '--header') && i + 1 < tokens.length) {
                    const headerValue = tokens[i + 1].replace(/^['"]|['"]$/g, '');
                    const colonIndex = headerValue.indexOf(':');
                    if (colonIndex > 0) {
                        const key = headerValue.substring(0, colonIndex).trim();
                        const value = headerValue.substring(colonIndex + 1).trim();
                        config.headers[key] = value;
                    }
                    i++;
                    continue;
                }
                
                // 请求体数据
                if ((token === '-d' || token === '--data' || token === '--data-raw') && i + 1 < tokens.length) {
                    let bodyData = tokens[i + 1];
                    
                    // 移除外层引号
                    if ((bodyData.startsWith('"') && bodyData.endsWith('"')) ||
                        (bodyData.startsWith("'") && bodyData.endsWith("'"))) {
                        bodyData = bodyData.slice(1, -1);
                    }
                    
                    config.body = bodyData;
                    
                    // 如果没有设置方法，默认为POST
                    if (config.method === 'GET') {
                        config.method = 'POST';
                    }
                    i++;
                    continue;
                }
                
                // URL - 通常是不带 - 前缀的参数
                if (!token.startsWith('-') && !config.url && 
                    !['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'].includes(token.toUpperCase())) {
                    config.url = token.replace(/^['"]|['"]$/g, '');
                }
            }

            // 验证必要字段
            if (!config.url) {
                return { success: false, error: '未找到有效的URL' };
            }

            return {
                success: true,
                data: config
            };
        } catch (error) {
            return { success: false, error: `cURL解析失败: ${error.message}` };
        }
    }

    // 分词器 - 正确处理引号内的内容
    static tokenizeCurlCommand(command) {
        const tokens = [];
        let current = '';
        let inQuotes = false;
        let quoteChar = '';
        
        for (let i = 0; i < command.length; i++) {
            const char = command[i];
            const prevChar = i > 0 ? command[i - 1] : '';
            
            if ((char === '"' || char === "'") && prevChar !== '\\') {
                if (!inQuotes) {
                    // 开始引号
                    if (current.trim()) {
                        tokens.push(current.trim());
                        current = '';
                    }
                    inQuotes = true;
                    quoteChar = char;
                    current += char;
                } else if (char === quoteChar) {
                    // 结束引号
                    current += char;
                    tokens.push(current);
                    current = '';
                    inQuotes = false;
                    quoteChar = '';
                } else {
                    // 引号内的其他引号
                    current += char;
                }
            } else if (char === ' ' && !inQuotes) {
                // 空格分割
                if (current.trim()) {
                    tokens.push(current.trim());
                    current = '';
                }
            } else {
                current += char;
            }
        }
        
        // 添加最后一个token
        if (current.trim()) {
            tokens.push(current.trim());
        }
        
        return tokens;
    }

    // 生成cURL命令
    static generateCurl(config) {
        try {
            const { url, method = 'GET', headers = {}, body } = config;
            
            let curl = `curl -X ${method.toUpperCase()}`;
            
            // 添加请求头
            Object.entries(headers).forEach(([key, value]) => {
                curl += ` -H "${key}: ${value}"`;
            });
            
            // 添加请求体
            if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
                curl += ` -d '${body}'`;
            }
            
            // 添加URL
            curl += ` "${url}"`;
            
            return {
                success: true,
                data: curl
            };
        } catch (error) {
            return { success: false, error: `cURL生成失败: ${error.message}` };
        }
    }

    // 格式化响应数据
    static formatResponse(response, format = 'auto') {
        try {
            if (!response || !response.body) {
                return { success: false, error: '响应数据为空' };
            }

            let formatted = response.body;
            let detectedFormat = 'text';

            // 自动检测格式
            if (format === 'auto') {
                const contentType = response.headers['content-type'] || '';
                
                if (contentType.includes('application/json')) {
                    format = 'json';
                } else if (contentType.includes('text/html')) {
                    format = 'html';
                } else if (contentType.includes('application/xml') || contentType.includes('text/xml')) {
                    format = 'xml';
                } else {
                    format = 'text';
                }
            }

            // 格式化处理
            switch (format) {
                case 'json':
                    try {
                        const parsed = typeof response.body === 'string' 
                            ? JSON.parse(response.body)
                            : response.body;
                        formatted = JSON.stringify(parsed, null, 2);
                        detectedFormat = 'json';
                    } catch (e) {
                        formatted = response.body;
                        detectedFormat = 'text';
                    }
                    break;
                    
                case 'xml':
                case 'html':
                    // 简单的XML/HTML格式化
                    formatted = response.body
                        .replace(/></g, '>\n<')
                        .replace(/^\s*\n/gm, '');
                    detectedFormat = format;
                    break;
                    
                default:
                    formatted = response.body;
                    detectedFormat = 'text';
            }

            return {
                success: true,
                data: {
                    formatted: formatted,
                    original: response.body,
                    format: detectedFormat,
                    size: new Blob([formatted]).size
                }
            };
        } catch (error) {
            return { success: false, error: `响应格式化失败: ${error.message}` };
        }
    }

    // 获取响应状态信息
    static getStatusInfo(status) {
        const statusMap = {
            // 1xx 信息响应
            100: { type: 'info', message: 'Continue - 继续' },
            101: { type: 'info', message: 'Switching Protocols - 切换协议' },
            
            // 2xx 成功
            200: { type: 'success', message: 'OK - 请求成功' },
            201: { type: 'success', message: 'Created - 已创建' },
            202: { type: 'success', message: 'Accepted - 已接受' },
            204: { type: 'success', message: 'No Content - 无内容' },
            
            // 3xx 重定向
            301: { type: 'warning', message: 'Moved Permanently - 永久重定向' },
            302: { type: 'warning', message: 'Found - 临时重定向' },
            304: { type: 'warning', message: 'Not Modified - 未修改' },
            
            // 4xx 客户端错误
            400: { type: 'error', message: 'Bad Request - 请求错误' },
            401: { type: 'error', message: 'Unauthorized - 未授权' },
            403: { type: 'error', message: 'Forbidden - 禁止访问' },
            404: { type: 'error', message: 'Not Found - 资源未找到' },
            405: { type: 'error', message: 'Method Not Allowed - 方法不允许' },
            429: { type: 'error', message: 'Too Many Requests - 请求过多' },
            
            // 5xx 服务器错误
            500: { type: 'error', message: 'Internal Server Error - 服务器内部错误' },
            502: { type: 'error', message: 'Bad Gateway - 网关错误' },
            503: { type: 'error', message: 'Service Unavailable - 服务不可用' },
            504: { type: 'error', message: 'Gateway Timeout - 网关超时' }
        };

        return statusMap[status] || { 
            type: status < 400 ? 'success' : 'error', 
            message: `HTTP ${status}` 
        };
    }

    // 保存请求历史
    static saveToHistory(config, response) {
        try {
            const historyKey = 'api-tester-history';
            let history = JSON.parse(localStorage.getItem(historyKey) || '[]');
            
            const item = {
                id: Date.now(),
                timestamp: new Date().toISOString(),
                config: config,
                response: {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers,
                    size: response.size,
                    duration: response.duration
                }
            };
            
            // 最多保存50条历史记录
            history.unshift(item);
            history = history.slice(0, 50);
            
            localStorage.setItem(historyKey, JSON.stringify(history));
            
            return { success: true, data: history };
        } catch (error) {
            return { success: false, error: `保存历史记录失败: ${error.message}` };
        }
    }

    // 获取请求历史
    static getHistory() {
        try {
            const historyKey = 'api-tester-history';
            const history = JSON.parse(localStorage.getItem(historyKey) || '[]');
            return { success: true, data: history };
        } catch (error) {
            return { success: false, error: `获取历史记录失败: ${error.message}` };
        }
    }

    // 清空历史记录
    static clearHistory() {
        try {
            localStorage.removeItem('api-tester-history');
            return { success: true, data: [] };
        } catch (error) {
            return { success: false, error: `清空历史记录失败: ${error.message}` };
        }
    }

    // 导出请求集合
    static exportCollection(requests) {
        try {
            const collection = {
                name: 'API测试集合',
                description: '从DevTools导出的API请求集合',
                timestamp: new Date().toISOString(),
                requests: requests
            };

            const blob = new Blob([JSON.stringify(collection, null, 2)], {
                type: 'application/json'
            });
            
            return {
                success: true,
                data: {
                    blob: blob,
                    filename: `api-collection-${new Date().toISOString().slice(0, 10)}.json`
                }
            };
        } catch (error) {
            return { success: false, error: `导出失败: ${error.message}` };
        }
    }

    // 环境变量相关方法
    static getEnvironments() {
        try {
            const stored = localStorage.getItem('api-tester-environments');
            if (stored) {
                this.environments = JSON.parse(stored);
            }
            return { success: true, data: this.environments };
        } catch (error) {
            return { success: false, error: `获取环境变量失败: ${error.message}` };
        }
    }

    static setEnvironment(name, variables) {
        try {
            this.environments.list[name] = {
                name: name,
                variables: variables || {}
            };
            localStorage.setItem('api-tester-environments', JSON.stringify(this.environments));
            return { success: true, data: this.environments.list[name] };
        } catch (error) {
            return { success: false, error: `设置环境变量失败: ${error.message}` };
        }
    }

    static switchEnvironment(name) {
        if (this.environments.list[name]) {
            this.environments.current = name;
            localStorage.setItem('api-tester-environments', JSON.stringify(this.environments));
            return { success: true, data: name };
        }
        return { success: false, error: '环境不存在' };
    }

    static deleteEnvironment(name) {
        if (name === 'default') {
            return { success: false, error: '不能删除默认环境' };
        }
        if (this.environments.list[name]) {
            delete this.environments.list[name];
            if (this.environments.current === name) {
                this.environments.current = 'default';
            }
            localStorage.setItem('api-tester-environments', JSON.stringify(this.environments));
            return { success: true };
        }
        return { success: false, error: '环境不存在' };
    }

    // 变量替换功能
    static replaceVariables(text) {
        if (typeof text !== 'string') return text;
        
        let result = text;
        const currentEnv = this.environments.list[this.environments.current] || { variables: {} };
        
        // 替换环境变量 {{variable}}
        result = result.replace(/\{\{([^}]+)\}\}/g, (match, varName) => {
            const trimmedName = varName.trim();
            // 优先级：全局变量 > 环境变量
            return this.globalVariables[trimmedName] || 
                   currentEnv.variables[trimmedName] || 
                   match; // 保持原样如果找不到变量
        });
        
        return result;
    }

    // Pre-request 脚本执行
    static async executePreRequestScript(script, context = {}) {
        if (!script) return { success: true, data: context };
        
        try {
            // 创建沙箱环境
            const sandbox = {
                pm: {
                    environment: {
                        get: (key) => this.environments.list[this.environments.current]?.variables[key],
                        set: (key, value) => {
                            if (!this.environments.list[this.environments.current]) {
                                this.environments.list[this.environments.current] = { variables: {} };
                            }
                            this.environments.list[this.environments.current].variables[key] = value;
                        }
                    },
                    globals: {
                        get: (key) => this.globalVariables[key],
                        set: (key, value) => { this.globalVariables[key] = value; }
                    },
                    variables: {
                        get: (key) => context.variables?.[key],
                        set: (key, value) => { 
                            if (!context.variables) context.variables = {};
                            context.variables[key] = value; 
                        }
                    },
                    request: context.request || {},
                    sendRequest: (config) => this.sendRequest(config)
                },
                console: {
                    log: (...args) => console.log('[Pre-request Script]', ...args),
                    error: (...args) => console.error('[Pre-request Script]', ...args)
                },
                Date,
                Math,
                JSON,
                btoa,
                atob
            };
            
            // 执行脚本
            const func = new Function('pm', 'console', 'Date', 'Math', 'JSON', 'btoa', 'atob', script);
            await func(sandbox.pm, sandbox.console, Date, Math, JSON, btoa, atob);
            
            return { success: true, data: context };
        } catch (error) {
            return { success: false, error: `Pre-request脚本执行失败: ${error.message}` };
        }
    }

    // 测试脚本执行
    static async executeTestScript(script, response, context = {}) {
        if (!script) return { success: true, data: { tests: {} } };
        
        try {
            const tests = {};
            const sandbox = {
                pm: {
                    test: (name, func) => {
                        try {
                            func();
                            tests[name] = { status: 'passed', error: null };
                        } catch (error) {
                            tests[name] = { status: 'failed', error: error.message };
                        }
                    },
                    expect: (actual) => {
                        return {
                            to: {
                                equal: (expected) => {
                                    if (actual !== expected) {
                                        throw new Error(`期望 ${actual} 等于 ${expected}`);
                                    }
                                },
                                be: {
                                    oneOf: (array) => {
                                        if (!array.includes(actual)) {
                                            throw new Error(`期望 ${actual} 在 [${array.join(', ')}] 中`);
                                        }
                                    }
                                },
                                have: {
                                    property: (prop) => {
                                        if (!actual.hasOwnProperty(prop)) {
                                            throw new Error(`期望对象包含属性 ${prop}`);
                                        }
                                    }
                                }
                            }
                        };
                    },
                    response: {
                        code: response.status,
                        status: response.statusText,
                        headers: response.headers,
                        responseTime: response.duration,
                        responseSize: response.size,
                        text: () => response.body,
                        json: () => {
                            try {
                                return JSON.parse(response.body);
                            } catch (e) {
                                throw new Error('响应不是有效的JSON格式');
                            }
                        }
                    },
                    environment: {
                        get: (key) => this.environments.list[this.environments.current]?.variables[key],
                        set: (key, value) => {
                            if (!this.environments.list[this.environments.current]) {
                                this.environments.list[this.environments.current] = { variables: {} };
                            }
                            this.environments.list[this.environments.current].variables[key] = value;
                        }
                    },
                    globals: {
                        get: (key) => this.globalVariables[key],
                        set: (key, value) => { this.globalVariables[key] = value; }
                    }
                },
                console: {
                    log: (...args) => console.log('[Test Script]', ...args),
                    error: (...args) => console.error('[Test Script]', ...args)
                },
                JSON,
                Date,
                Math
            };
            
            // 执行脚本
            const func = new Function('pm', 'console', 'JSON', 'Date', 'Math', script);
            await func(sandbox.pm, sandbox.console, JSON, Date, Math);
            
            return { success: true, data: { tests } };
        } catch (error) {
            return { success: false, error: `测试脚本执行失败: ${error.message}` };
        }
    }

    // 批量运行请求集合
    static async runCollection(collection, environment = null) {
        const results = [];
        const startTime = Date.now();
        
        try {
            // 临时切换环境
            const originalEnv = this.environments.current;
            if (environment && this.environments.list[environment]) {
                this.environments.current = environment;
            }
            
            for (const request of collection.requests) {
                const requestResult = {
                    name: request.name || 'Unnamed Request',
                    startTime: Date.now()
                };
                
                try {
                    // 执行pre-request脚本
                    const preScriptResult = await this.executePreRequestScript(
                        request.preRequestScript, 
                        { request: request.config }
                    );
                    
                    if (!preScriptResult.success) {
                        throw new Error(preScriptResult.error);
                    }
                    
                    // 发送请求
                    const response = await this.sendRequest(request.config);
                    
                    if (response.success) {
                        requestResult.response = response.data.response;
                        requestResult.success = true;
                        
                        // 执行测试脚本
                        const testResult = await this.executeTestScript(
                            request.testScript,
                            response.data.response
                        );
                        
                        requestResult.tests = testResult.success ? testResult.data.tests : {};
                        requestResult.testError = testResult.success ? null : testResult.error;
                    } else {
                        requestResult.success = false;
                        requestResult.error = response.error;
                    }
                } catch (error) {
                    requestResult.success = false;
                    requestResult.error = error.message;
                }
                
                requestResult.duration = Date.now() - requestResult.startTime;
                results.push(requestResult);
            }
            
            // 恢复原环境
            this.environments.current = originalEnv;
            
            return {
                success: true,
                data: {
                    results,
                    summary: {
                        total: results.length,
                        passed: results.filter(r => r.success).length,
                        failed: results.filter(r => !r.success).length,
                        duration: Date.now() - startTime
                    }
                }
            };
        } catch (error) {
            return { success: false, error: `集合运行失败: ${error.message}` };
        }
    }

    // 性能分析
    static analyzePerformance(responses) {
        if (!Array.isArray(responses) || responses.length === 0) {
            return { success: false, error: '没有响应数据可分析' };
        }
        
        const durations = responses.map(r => r.duration).filter(d => d > 0);
        const sizes = responses.map(r => r.size).filter(s => s > 0);
        
        return {
            success: true,
            data: {
                requests: {
                    total: responses.length,
                    successful: responses.filter(r => r.status >= 200 && r.status < 400).length,
                    failed: responses.filter(r => r.status >= 400).length
                },
                timing: {
                    average: durations.length ? Math.round(durations.reduce((a, b) => a + b, 0) / durations.length) : 0,
                    min: durations.length ? Math.min(...durations) : 0,
                    max: durations.length ? Math.max(...durations) : 0,
                    median: durations.length ? durations.sort()[Math.floor(durations.length / 2)] : 0
                },
                size: {
                    average: sizes.length ? Math.round(sizes.reduce((a, b) => a + b, 0) / sizes.length) : 0,
                    min: sizes.length ? Math.min(...sizes) : 0,
                    max: sizes.length ? Math.max(...sizes) : 0,
                    total: sizes.reduce((a, b) => a + b, 0)
                },
                statusCodes: responses.reduce((acc, r) => {
                    const status = Math.floor(r.status / 100) * 100;
                    acc[`${status}xx`] = (acc[`${status}xx`] || 0) + 1;
                    return acc;
                }, {})
            }
        };
    }

    // 代码生成器 - 扩展版
    static generateCode(config, language = 'curl') {
        try {
            switch (language) {
                case 'curl':
                    return this.generateCurl(config);
                case 'javascript':
                    return this.generateJavaScript(config);
                case 'javascript-axios':
                    return this.generateJavaScriptAxios(config);
                case 'javascript-jquery':
                    return this.generateJavaScriptJQuery(config);
                case 'python':
                    return this.generatePython(config);
                case 'python-urllib':
                    return this.generatePythonUrllib(config);
                case 'nodejs':
                    return this.generateNodeJS(config);
                case 'nodejs-axios':
                    return this.generateNodeJSAxios(config);
                case 'php':
                    return this.generatePHP(config);
                case 'php-guzzle':
                    return this.generatePHPGuzzle(config);
                case 'java':
                    return this.generateJava(config);
                case 'csharp':
                    return this.generateCSharp(config);
                case 'go':
                    return this.generateGo(config);
                case 'ruby':
                    return this.generateRuby(config);
                case 'swift':
                    return this.generateSwift(config);
                case 'kotlin':
                    return this.generateKotlin(config);
                default:
                    return { success: false, error: '不支持的代码语言' };
            }
        } catch (error) {
            return { success: false, error: `代码生成失败: ${error.message}` };
        }
    }

    // 生成JavaScript代码
    static generateJavaScript(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        
        let code = `fetch('${url}', {\n`;
        code += `  method: '${method.toUpperCase()}',\n`;
        
        if (Object.keys(headers).length > 0) {
            code += `  headers: {\n`;
            Object.entries(headers).forEach(([key, value]) => {
                code += `    '${key}': '${value}',\n`;
            });
            code += `  },\n`;
        }
        
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            if (typeof body === 'string') {
                code += `  body: '${body.replace(/'/g, "\\'")}'\n`;
            } else {
                code += `  body: JSON.stringify(${JSON.stringify(body, null, 2)})\n`;
            }
        }
        
        code += `})\n.then(response => response.json())\n.then(data => console.log(data))\n.catch(error => console.error('Error:', error));`;
        
        return { success: true, data: code };
    }

    // 生成Python代码
    static generatePython(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        
        let code = `import requests\nimport json\n\n`;
        code += `url = "${url}"\n`;
        
        if (Object.keys(headers).length > 0) {
            code += `headers = {\n`;
            Object.entries(headers).forEach(([key, value]) => {
                code += `    "${key}": "${value}",\n`;
            });
            code += `}\n\n`;
        } else {
            code += `headers = {}\n\n`;
        }
        
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            if (typeof body === 'string') {
                try {
                    JSON.parse(body);
                    code += `data = ${body}\n\n`;
                } catch (e) {
                    code += `data = "${body.replace(/"/g, '\\"')}"\n\n`;
                }
            } else {
                code += `data = ${JSON.stringify(body, null, 2)}\n\n`;
            }
            code += `response = requests.${method.toLowerCase()}(url, headers=headers, json=data)\n`;
        } else {
            code += `response = requests.${method.toLowerCase()}(url, headers=headers)\n`;
        }
        
        code += `print(f"Status Code: {response.status_code}")\nprint(f"Response: {response.text}")`;
        
        return { success: true, data: code };
    }

    // 生成Node.js代码
    static generateNodeJS(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        
        let code = `const https = require('https');\nconst http = require('http');\n\n`;
        code += `const url = require('url');\nconst parsedUrl = url.parse('${url}');\n\n`;
        
        code += `const options = {\n`;
        code += `  hostname: parsedUrl.hostname,\n`;
        code += `  port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),\n`;
        code += `  path: parsedUrl.path,\n`;
        code += `  method: '${method.toUpperCase()}',\n`;
        
        if (Object.keys(headers).length > 0) {
            code += `  headers: {\n`;
            Object.entries(headers).forEach(([key, value]) => {
                code += `    '${key}': '${value}',\n`;
            });
            code += `  }\n`;
        }
        
        code += `};\n\n`;
        
        code += `const client = parsedUrl.protocol === 'https:' ? https : http;\n`;
        code += `const req = client.request(options, (res) => {\n`;
        code += `  console.log('Status Code:', res.statusCode);\n`;
        code += `  res.on('data', (chunk) => {\n`;
        code += `    console.log(chunk.toString());\n`;
        code += `  });\n`;
        code += `});\n\n`;
        
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            if (typeof body === 'string') {
                code += `req.write('${body.replace(/'/g, "\\'")}'');\n`;
            } else {
                code += `req.write(JSON.stringify(${JSON.stringify(body, null, 2)}));\n`;
            }
        }
        
        code += `req.on('error', (error) => {\n`;
        code += `  console.error('Error:', error);\n`;
        code += `});\n\n`;
        code += `req.end();`;
        
        return { success: true, data: code };
    }

    // JavaScript Axios
    static generateJavaScriptAxios(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        
        let code = `const axios = require('axios');\n\n`;
        code += `const config = {\n`;
        code += `  method: '${method.toLowerCase()}',\n`;
        code += `  url: '${url}',\n`;
        
        if (Object.keys(headers).length > 0) {
            code += `  headers: {\n`;
            Object.entries(headers).forEach(([key, value]) => {
                code += `    '${key}': '${value}',\n`;
            });
            code += `  },\n`;
        }
        
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            code += `  data: ${typeof body === 'string' && body.startsWith('{') ? body : `'${body}'`}\n`;
        }
        
        code += `};\n\n`;
        code += `axios(config)\n.then(response => {\n  console.log(response.data);\n})\n.catch(error => {\n  console.error(error);\n});`;
        
        return { success: true, data: code };
    }

    // JavaScript jQuery
    static generateJavaScriptJQuery(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        
        let code = `$.ajax({\n`;
        code += `  url: '${url}',\n`;
        code += `  method: '${method.toUpperCase()}',\n`;
        
        if (Object.keys(headers).length > 0) {
            code += `  headers: {\n`;
            Object.entries(headers).forEach(([key, value]) => {
                code += `    '${key}': '${value}',\n`;
            });
            code += `  },\n`;
        }
        
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            code += `  data: ${typeof body === 'string' && body.startsWith('{') ? body : `'${body}'`},\n`;
        }
        
        code += `  success: function(data) {\n    console.log(data);\n  },\n`;
        code += `  error: function(xhr, status, error) {\n    console.error('Error:', error);\n  }\n});`;
        
        return { success: true, data: code };
    }

    // Python urllib
    static generatePythonUrllib(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        
        let code = `import urllib.request\nimport json\n\n`;
        code += `url = "${url}"\n`;
        
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            code += `data = ${typeof body === 'string' && body.startsWith('{') ? body : `"${body}"`}\n`;
            code += `data = data.encode('utf-8') if isinstance(data, str) else json.dumps(data).encode('utf-8')\n\n`;
        }
        
        code += `req = urllib.request.Request(url`;
        if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
            code += `, data=data`;
        }
        code += `, method='${method.toUpperCase()}')\n\n`;
        
        if (Object.keys(headers).length > 0) {
            Object.entries(headers).forEach(([key, value]) => {
                code += `req.add_header('${key}', '${value}')\n`;
            });
            code += `\n`;
        }
        
        code += `try:\n    with urllib.request.urlopen(req) as response:\n        result = response.read().decode('utf-8')\n        print(result)\nexcept Exception as e:\n    print(f"Error: {e}")`;
        
        return { success: true, data: code };
    }

    // 其他语言生成方法的简化版本（由于篇幅限制）
    static generateNodeJSAxios(config) {
        return this.generateJavaScriptAxios(config);
    }

    static generatePHP(config) {
        const { url, method = 'GET', headers = {}, body } = config;
        let code = `<?php\n$curl = curl_init();\ncurl_setopt_array($curl, [\n    CURLOPT_URL => "${url}",\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => "${method.toUpperCase()}",\n`;
        if (body) code += `    CURLOPT_POSTFIELDS => '${body}',\n`;
        if (Object.keys(headers).length > 0) {
            code += `    CURLOPT_HTTPHEADER => [${Object.entries(headers).map(([k,v]) => `"${k}: ${v}"`).join(', ')}],\n`;
        }
        code += `]);\n$response = curl_exec($curl);\ncurl_close($curl);\necho $response;\n?>`;
        return { success: true, data: code };
    }

    static generatePHPGuzzle(config) {
        const { url, method = 'GET', body } = config;
        let code = `<?php\nuse GuzzleHttp\\Client;\n$client = new Client();\n$response = $client->request('${method}', '${url}'`;
        if (body) code += `, ['body' => '${body}']`;
        code += `);\necho $response->getBody();\n?>`;
        return { success: true, data: code };
    }

    static generateJava(config) {
        const { url, method = 'GET' } = config;
        return { success: true, data: `// Java代码 (需要OkHttp依赖)\nOkHttpClient client = new OkHttpClient();\nRequest request = new Request.Builder().url("${url}").${method.toLowerCase()}().build();\nResponse response = client.newCall(request).execute();` };
    }

    static generateCSharp(config) {
        const { url, method = 'GET' } = config;
        return { success: true, data: `// C# 代码\nusing var client = new HttpClient();\nvar response = await client.${method === 'GET' ? 'GetAsync' : 'PostAsync'}("${url}");\nvar content = await response.Content.ReadAsStringAsync();` };
    }

    static generateGo(config) {
        const { url, method = 'GET' } = config;
        return { success: true, data: `// Go 代码\nresp, err := http.${method === 'GET' ? 'Get' : 'Post'}("${url}")\nif err != nil { log.Fatal(err) }\ndefer resp.Body.Close()` };
    }

    static generateRuby(config) {
        const { url } = config;
        return { success: true, data: `# Ruby 代码\nrequire 'net/http'\nuri = URI('${url}')\nresponse = Net::HTTP.get_response(uri)\nputs response.body` };
    }

    static generateSwift(config) {
        const { url } = config;
        return { success: true, data: `// Swift 代码\nlet url = URL(string: "${url}")!\nlet task = URLSession.shared.dataTask(with: url)\ntask.resume()` };
    }

    static generateKotlin(config) {
        const { url } = config;
        return { success: true, data: `// Kotlin 代码 (需要OkHttp)\nval client = OkHttpClient()\nval request = Request.Builder().url("${url}").build()\nval response = client.newCall(request).execute()` };
    }

    // 请求模拟和Mock
    static createMockServer(responses) {
        // 这里可以创建一个简单的mock服务器配置
        return {
            success: true,
            data: {
                mockConfig: responses,
                instructions: '将此配置导入到mock服务器工具中使用'
            }
        };
    }

    // 历史记录管理
    static getHistory() {
        try {
            const stored = localStorage.getItem('api-tester-history');
            const history = stored ? JSON.parse(stored) : [];
            return { success: true, data: history };
        } catch (error) {
            return { success: false, error: `获取历史记录失败: ${error.message}` };
        }
    }

    static saveToHistory(config, response) {
        try {
            const history = this.getHistory();
            if (history.success) {
                const newItem = {
                    config,
                    response,
                    timestamp: new Date().toISOString()
                };
                
                // 限制历史记录数量为100条
                const updatedHistory = [newItem, ...history.data].slice(0, 100);
                localStorage.setItem('api-tester-history', JSON.stringify(updatedHistory));
                return { success: true };
            }
            return history;
        } catch (error) {
            return { success: false, error: `保存历史记录失败: ${error.message}` };
        }
    }

    static clearHistory() {
        try {
            localStorage.removeItem('api-tester-history');
            return { success: true };
        } catch (error) {
            return { success: false, error: `清空历史记录失败: ${error.message}` };
        }
    }

    // 状态信息获取
    static getStatusInfo(status) {
        if (status >= 200 && status < 300) {
            return { type: 'success', message: '成功' };
        } else if (status >= 300 && status < 400) {
            return { type: 'info', message: '重定向' };
        } else if (status >= 400 && status < 500) {
            return { type: 'warning', message: '客户端错误' };
        } else if (status >= 500) {
            return { type: 'error', message: '服务器错误' };
        } else {
            return { type: 'info', message: '未知状态' };
        }
    }

    // 格式化响应
    static formatResponse(response) {
        try {
            const body = response.body;
            let formatted = body;
            
            // 尝试格式化JSON
            try {
                const jsonObj = JSON.parse(body);
                formatted = JSON.stringify(jsonObj, null, 2);
            } catch (e) {
                // 不是JSON，保持原样
            }
            
            return { success: true, data: { formatted } };
        } catch (error) {
            return { success: false, error: `格式化失败: ${error.message}` };
        }
    }

    // cURL解析
    static parseCurl(curlCommand) {
        try {
            const config = {
                method: 'GET',
                url: '',
                headers: {},
                body: null
            };
            
            // 简单的cURL解析（可以扩展更复杂的解析逻辑）
            const parts = curlCommand.split(/\s+/);
            
            for (let i = 0; i < parts.length; i++) {
                const part = parts[i];
                
                if (part === '-X' || part === '--request') {
                    config.method = parts[i + 1];
                    i++;
                } else if (part === '-H' || part === '--header') {
                    const headerStr = parts[i + 1].replace(/['"]/g, '');
                    const [key, ...valueParts] = headerStr.split(':');
                    if (key && valueParts.length > 0) {
                        config.headers[key.trim()] = valueParts.join(':').trim();
                    }
                    i++;
                } else if (part === '-d' || part === '--data') {
                    config.body = parts[i + 1].replace(/['"]/g, '');
                    i++;
                } else if (part.startsWith('http')) {
                    config.url = part.replace(/['"]/g, '');
                }
            }
            
            return { success: true, data: config };
        } catch (error) {
            return { success: false, error: `cURL解析失败: ${error.message}` };
        }
    }

    // 生成cURL命令
    static generateCurl(config) {
        try {
            const { url, method = 'GET', headers = {}, body } = config;
            
            let curlCommand = `curl -X ${method.toUpperCase()} '${url}'`;
            
            // 添加请求头
            Object.entries(headers).forEach(([key, value]) => {
                curlCommand += ` -H '${key}: ${value}'`;
            });
            
            // 添加请求体
            if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
                curlCommand += ` -d '${body.replace(/'/g, "'\"'\"'")}'`;
            }
            
            return { success: true, data: curlCommand };
        } catch (error) {
            return { success: false, error: `cURL生成失败: ${error.message}` };
        }
    }

    // 导出集合
    static exportCollection(items) {
        try {
            const collection = {
                info: {
                    name: 'API测试集合',
                    description: '从API测试工具导出的请求集合',
                    version: '1.0.0'
                },
                requests: items.map(item => ({
                    name: `${item.config.method} ${item.config.url}`,
                    config: item.config,
                    response: item.response,
                    timestamp: item.timestamp
                }))
            };
            
            const blob = new Blob([JSON.stringify(collection, null, 2)], {
                type: 'application/json'
            });
            
            return {
                success: true,
                data: {
                    blob: blob,
                    filename: `api-collection-${new Date().toISOString().slice(0, 10)}.json`
                }
            };
        } catch (error) {
            return { success: false, error: `导出失败: ${error.message}` };
        }
    }

    // 预设请求模板 - 扩展版
    static getTemplates() {
        return {
            success: true,
            data: {
                'rest-get': {
                    name: 'REST API - GET请求',
                    config: {
                        url: 'https://jsonplaceholder.typicode.com/posts/1',
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json'
                        }
                    }
                },
                'rest-post': {
                    name: 'REST API - POST请求',
                    config: {
                        url: 'https://jsonplaceholder.typicode.com/posts',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            title: '测试标题',
                            body: '测试内容',
                            userId: 1
                        }, null, 2)
                    }
                },
                'form-data': {
                    name: '表单数据提交',
                    config: {
                        url: 'https://httpbin.org/post',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'name=测试用户&email=test@example.com'
                    }
                },
                'auth-bearer': {
                    name: 'Bearer Token认证',
                    config: {
                        url: 'https://api.example.com/user/profile',
                        method: 'GET',
                        headers: {
                            'Authorization': 'Bearer {{token}}',
                            'Accept': 'application/json'
                        }
                    }
                },
                'file-upload': {
                    name: '文件上传',
                    config: {
                        url: 'https://httpbin.org/post',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                        body: 'file=@example.jpg&description=测试文件'
                    }
                },
                'graphql': {
                    name: 'GraphQL查询',
                    config: {
                        url: 'https://api.example.com/graphql',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            query: `query GetUser($id: ID!) {\n  user(id: $id) {\n    id\n    name\n    email\n  }\n}`,
                            variables: { id: "1" }
                        }, null, 2)
                    }
                }
            }
        };
    }

    // 响应格式化功能
    static formatResponse(content, format) {
        try {
            switch (format) {
                case 'json':
                    return this.formatJSON(content);
                case 'xml':
                    return this.formatXML(content);
                case 'html':
                    return this.formatHTML(content);
                case 'csv':
                    return this.formatCSV(content);
                case 'auto':
                    return this.autoFormatResponse(content);
                default:
                    return { success: true, data: content, type: 'text' };
            }
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    // JSON格式化
    static formatJSON(content) {
        try {
            const parsed = JSON.parse(content);
            const formatted = JSON.stringify(parsed, null, 2);
            const highlighted = this.highlightJSON(formatted);
            return { 
                success: true, 
                data: highlighted, 
                type: 'json',
                raw: formatted,
                size: formatted.length,
                lines: formatted.split('\n').length
            };
        } catch (error) {
            return { success: false, error: '无效的JSON格式' };
        }
    }

    // XML格式化
    static formatXML(content) {
        try {
            // 简单的XML格式化
            let formatted = content
                .replace(/>\s*</g, '>\n<')  // 在标签间添加换行
                .replace(/^\s*\n/gm, '');   // 移除空行
            
            // 添加缩进
            let indent = 0;
            formatted = formatted.split('\n').map(line => {
                if (line.match(/^\s*<\/\w/)) {
                    indent--;
                }
                const indented = '  '.repeat(Math.max(0, indent)) + line.trim();
                if (line.match(/^\s*<\w[^>]*[^\/]>.*$/)) {
                    indent++;
                }
                return indented;
            }).join('\n');

            const highlighted = this.highlightXML(formatted);
            return {
                success: true,
                data: highlighted,
                type: 'xml',
                raw: formatted,
                size: formatted.length,
                lines: formatted.split('\n').length
            };
        } catch (error) {
            return { success: false, error: 'XML格式化失败' };
        }
    }

    // HTML格式化
    static formatHTML(content) {
        try {
            // 简单的HTML格式化
            let formatted = content
                .replace(/>\s*</g, '>\n<')
                .replace(/^\s*\n/gm, '');
            
            // 添加缩进
            let indent = 0;
            const voidElements = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
            
            formatted = formatted.split('\n').map(line => {
                const trimmed = line.trim();
                if (trimmed.match(/^\s*<\/\w/)) {
                    indent--;
                }
                const indented = '  '.repeat(Math.max(0, indent)) + trimmed;
                
                // 检查是否为开始标签且不是自闭合标签
                const tagMatch = trimmed.match(/^\s*<(\w+)(?:\s[^>]*)?>/);
                if (tagMatch && !voidElements.includes(tagMatch[1].toLowerCase()) && !trimmed.includes('</')) {
                    indent++;
                }
                return indented;
            }).join('\n');

            const highlighted = this.highlightHTML(formatted);
            return {
                success: true,
                data: highlighted,
                type: 'html',
                raw: formatted,
                size: formatted.length,
                lines: formatted.split('\n').length
            };
        } catch (error) {
            return { success: false, error: 'HTML格式化失败' };
        }
    }

    // CSV格式化
    static formatCSV(content) {
        try {
            const lines = content.split('\n').filter(line => line.trim());
            if (lines.length === 0) {
                return { success: false, error: '空的CSV内容' };
            }

            // 解析CSV
            const csvData = lines.map(line => {
                const cells = [];
                let current = '';
                let inQuotes = false;
                
                for (let i = 0; i < line.length; i++) {
                    const char = line[i];
                    if (char === '"') {
                        inQuotes = !inQuotes;
                    } else if (char === ',' && !inQuotes) {
                        cells.push(current.trim());
                        current = '';
                    } else {
                        current += char;
                    }
                }
                cells.push(current.trim());
                return cells;
            });

            // 生成表格HTML
            let tableHTML = '<div class="csv-table-container overflow-x-auto"><table class="min-w-full divide-y divide-gray-200">';
            
            if (csvData.length > 0) {
                // 表头
                tableHTML += '<thead class="bg-gray-50"><tr>';
                csvData[0].forEach((cell, index) => {
                    tableHTML += `<th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">列 ${index + 1}</th>`;
                });
                tableHTML += '</tr></thead>';

                // 表体
                tableHTML += '<tbody class="bg-white divide-y divide-gray-200">';
                csvData.forEach((row, rowIndex) => {
                    const bgClass = rowIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50';
                    tableHTML += `<tr class="${bgClass}">`;
                    row.forEach(cell => {
                        tableHTML += `<td class="px-4 py-2 whitespace-nowrap text-sm text-gray-900">${this.escapeHtml(cell)}</td>`;
                    });
                    tableHTML += '</tr>';
                });
                tableHTML += '</tbody>';
            }
            tableHTML += '</table></div>';

            return {
                success: true,
                data: tableHTML,
                type: 'csv',
                raw: content,
                size: content.length,
                lines: lines.length,
                rows: csvData.length,
                columns: csvData.length > 0 ? csvData[0].length : 0
            };
        } catch (error) {
            return { success: false, error: 'CSV格式化失败' };
        }
    }

    // 自动格式化检测
    static autoFormatResponse(content) {
        const trimmed = content.trim();
        
        // 检测JSON
        if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || 
            (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
            const jsonResult = this.formatJSON(content);
            if (jsonResult.success) return jsonResult;
        }
        
        // 检测XML
        if (trimmed.startsWith('<') && trimmed.includes('</')) {
            return this.formatXML(content);
        }
        
        // 检测HTML
        if (trimmed.toLowerCase().includes('<!doctype html') || 
            trimmed.toLowerCase().includes('<html')) {
            return this.formatHTML(content);
        }
        
        // 检测CSV（简单检测：包含逗号且多行）
        if (trimmed.includes(',') && trimmed.split('\n').length > 1) {
            const csvResult = this.formatCSV(content);
            if (csvResult.success) return csvResult;
        }
        
        // 默认返回纯文本
        return { 
            success: true, 
            data: this.escapeHtml(content), 
            type: 'text',
            raw: content,
            size: content.length,
            lines: content.split('\n').length
        };
    }

    // JSON语法高亮
    static highlightJSON(json) {
        return json
            .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (match) => {
                let cls = 'json-number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'json-key';
                    } else {
                        cls = 'json-string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'json-boolean';
                } else if (/null/.test(match)) {
                    cls = 'json-null';
                }
                return `<span class="${cls}">${match}</span>`;
            });
    }

    // XML语法高亮
    static highlightXML(xml) {
        return xml
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/&lt;(\/?[\w\-:]+)([^&gt;]*)&gt;/g, (match, tag, attrs) => {
                const highlightedAttrs = attrs.replace(/([\w\-:]+)=("[^"]*"|'[^']*')/g, 
                    '<span class="xml-attr-name">$1</span>=<span class="xml-attr-value">$2</span>');
                return `<span class="xml-tag">&lt;${tag}${highlightedAttrs}&gt;</span>`;
            });
    }

    // HTML语法高亮
    static highlightHTML(html) {
        return html
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/&lt;(!DOCTYPE[^&gt;]*)&gt;/gi, '<span class="html-doctype">&lt;$1&gt;</span>')
            .replace(/&lt;(\/?)(\w+)([^&gt;]*)&gt;/g, (match, slash, tag, attrs) => {
                const highlightedAttrs = attrs.replace(/([\w\-:]+)=("[^"]*"|'[^']*')/g, 
                    '<span class="html-attr-name">$1</span>=<span class="html-attr-value">$2</span>');
                return `<span class="html-tag">&lt;${slash}<span class="html-tag-name">${tag}</span>${highlightedAttrs}&gt;</span>`;
            });
    }

    // HTML转义
    static escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        };
        return text.replace(/[&<>"']/g, m => map[m]);
    }
}